<script setup>
import { onBeforeRouteUpdate, useRoute } from 'vue-router';
import axios from 'axios';
import config from '@/components/conf';
import { getCurrentInstance, ref, watchPostEffect } from 'vue';
import WelcomeItem from '@/components/WelcomeItem.vue';
import XEUtils, { isEmpty } from 'xe-utils';

import VueDatePicker from '@vuepic/vue-datepicker';
import '@vuepic/vue-datepicker/dist/main.css'
const { proxy } = getCurrentInstance();
const API_URL = config.URL;
const apps = ref(null);
const today = getDateFormatted(new Date());
const date = ref(today);
function updateStatistic(){
  const studentid = proxy.$userid;
  if(isEmpty(studentid)){
    return;
  }
  const url = `${API_URL}/api/mm/index/statistic?studentid=${studentid}&date=${date.value}`
  axios.get(url).then(
    (p)=>{
      var arr = p.data.data;
      var maxTime = 3600;
      arr.forEach(ap=>{
        if(maxTime<ap.useTime){
          maxTime = ap.useTime;
        }
      })
      
      arr.forEach(ap=>{
        var rate = ap.useTime*100/maxTime;
        ap.bar = 'width: '+rate+'%'
      })

      apps.value = p.data.data;
    })
}
onBeforeRouteUpdate(updateStatistic);

function getDateFormatted(now) {  
    return XEUtils.toDateString(now,"yyyy-MM-dd");
} 


function formatTime(num){
  var time = num%60 +"秒";
  if(num>=60){
    time = (num/60%60).toFixed()+"分钟"+time;
    if(num>=3600){
        time = (num/3600).toFixed()+"小时"+time;
    }
  }
  
  return time;
}
function warp_img(img){
  return '<img src="'+img+'" width="50px" height="50px"></img>';
}

updateStatistic();
const handleDate = (e)=>{
  date.value = getDateFormatted(date.value);
  console.log(date.value)
  updateStatistic();
}
</script>

<template>
  <main>
    
    <div class="container">
      <label class="h1 mt-3">选择日期:</label>
      <VueDatePicker v-model="date" class="c_ok" format="yyyy-MM-dd"  auto-apply locale="cn" @update:model-value="handleDate"></VueDatePicker>   
    </div>
    <li v-for="app in apps">
      <WelcomeItem :id="app.appId" :ratebar="app.bar" :useTime="formatTime(app.useTime)">
      <template #appImage>
        <span v-html=warp_img(app.appImage)></span>
      </template>
      <template #appName>
        {{ app.appName }}
      </template>
      <template #useTime>
        {{ formatTime(app.useTime) }}
      </template>
      
      </WelcomeItem>
    </li>
  </main>
</template>
<style>
li {
  list-style: none;
}

</style>